import JWTTool from "@/utils/frame/JWTTool";
import Store from "@/vue-config/store";
import { Permissions } from "@/model/frame/IPermissionConfig";
import FrameConfig from "@/model/frame/FrameConfig";

export interface ITokenPayload {
  id: string;
  username: string;
  permissions: string[];
}

export class SystemTool {
  public static decodeToken() {
    const _token = Store.get<string>("system/token");
    const _payload = JWTTool.webDecodeToken<ITokenPayload>(
      _token
    ) as ITokenPayload;
    this.fillInfo(_payload);
  }

  public static merginPermission(permission: Permissions) {
    const _default = Store.get<Permissions>("app/defaultPermissions");
    Store.set<Permissions>("app/permissions", [...permission, ..._default]);
  }

  public static setUsername(username: string): void {
    Store.set<string>("system/username", username);
  }

  public static setLogout(): void {
    Store.set<boolean>("system/isLogin", false);
    SystemTool.setUsername("");
    SystemTool.merginPermission([]);
  }

  public static systemStateLogout(): void {
    // 清理 Token
    localStorage.removeItem(FrameConfig.APP_TOKEN_NAME);
    SystemTool.setLogout();
  }

  private static fillInfo(_payload: ITokenPayload) {
    console.log("[Systemtool]:", _payload);
    SystemTool.merginPermission(_payload.permissions);
    SystemTool.setUsername(_payload.username);
  }
}
